﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace M_Ingredient.Repository
{
    public class IBaseRepository<T> : InRepository<T> where T : class, new()
    {
        protected readonly IMyDbcontract myDbcontract;

        public IBaseRepository(IMyDbcontract myDbcontract)
        {
            this.myDbcontract = myDbcontract;
        }
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> AddAsync(T entity)
        {
            await myDbcontract.AddAsync(entity);
            return await myDbcontract.SaveChangesAsync();
        }

        /// <summary>
        /// 获取实体列表
        /// </summary>
        /// <returns>返回实体列表</returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await myDbcontract.Set<T>().ToListAsync();
        }

        /// <summary>
        /// 根据条件获取实体列表
        /// </summary>
        /// <param name="expre">条件表达式</param>
        /// <returns>返回实体列表</returns>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await myDbcontract.Set<T>().Where(expre).ToListAsync();
        }

        /// <summary>
        /// 根据Id获取实体
        /// </summary>
        /// <param name="id">实体Id</param>
        /// <returns>实体</returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await myDbcontract.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> UpdateAsync(T entity)
        {
            myDbcontract.Update(entity);
            return await myDbcontract.SaveChangesAsync();
        }
    }
}
